package com.hruiworks.campusgroup.Interceptor;


import com.hruiworks.campusgroup.enums.ErrorCode;
import com.hruiworks.campusgroup.exception.BusinessException;
import com.hruiworks.campusgroup.pojo.entity.Administrator;
import com.hruiworks.usercheck.pojo.entity.JwtEntity;
import com.hruiworks.usercheck.util.JwtUtils;
import com.hruiworks.usercheck.util.ParamUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.hruiworks.campusgroup.constants.AdministratorConstant.*;

@Component
public class AdministratorInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String jwt = request.getHeader(ADMINISTRATOR_TOKEN);
        String secretKey = request.getHeader(ADMINISTRATOR_SECRET_KEY);
        if (ParamUtils.isAnyBlank(jwt,secretKey)) {
            throw new BusinessException(ErrorCode.NO_LOGIN);
        }
        Administrator administrator = JwtUtils.parseJwt(new JwtEntity(jwt, secretKey), Administrator.class);

        request.setAttribute(ADMINISTRATOR_INFO,administrator);
        return true;

    }
}
